package com.coocaa.launcher.wallpaper;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.coocaa.framework.ui.view.ScrollGridView;
import com.coocaa.launcher.LauncherBaseActivity;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.AsyncTask;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.litecontent.BroadcastAction;
import com.coocaa.x.service.litecontent.api.ContentApi;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_theme.RP_WallpaperCategory;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_theme.RP_WallpaperList;
import com.tianci.appstore.R;
import com.tianci.appstore.ui.widget.SkyAppPager;
import com.tianci.appstore.ui.widget.TipToast;

import java.util.HashMap;
import java.util.List;

/**
 * Created by luwei on 15-7-4.
 */
public class WallpaperController implements SkyAppPager.AnimListener, View.OnKeyListener, ScrollTitleBar.OnTitleSelectedListener,
        AdapterView.OnItemSelectedListener,AdapterView.OnItemClickListener{

    private SkyAppPager appPager = null;
    private WallpaperLayout layout = null;
    private boolean resetFocus = true;
    private Context context = null;
    private static WallpaperController instance = null;
    private int currentPage = 0;
    private static final int PAGE_COUNT = 12;
    private HashMap<String, List<RP_WallpaperList.WallPaper_Item>> wallpaper_items = new HashMap<String, List<RP_WallpaperList.WallPaper_Item>>();
    private List<RP_WallpaperCategory.WallPaper_Category_Item> category_items = null;
    private HashMap<String, SpannableString> tipsMap = new HashMap<String, SpannableString>();
    private int currentPos = 0;
    private boolean isPause = false;
    public static final String OWNWALLPAPER = "ownwallpaper";
    public static final String MYCOLLECTION = "mycollection";

    private WallpaperController(Context context) {
        this.context = context;
        IntentFilter filter = new IntentFilter();
        filter.addAction(BroadcastAction.WALLPAPERCHANGEDBROASTCAST);
        context.registerReceiver(wallpaperRecever, filter);

    }

    public synchronized static WallpaperController getInstance(Context context) {
        if (instance == null)
            instance = new WallpaperController(context);
        return instance;
    }

    public void setWallpaperLayout(WallpaperLayout layout) {
        this.layout = layout;
        appPager = layout.getAppPager();
        appPager.setAnimListener(this);
        layout.getTitleBar().setTitleSelectedListener(this);
        getCategory();
    }

    @Override
    public boolean onAnimStart(int current) {
        currentPos = 0;
        return false;
    }

    @Override
    public boolean onAnimEnd(int current) {
        ScrollGridView temp = ((ScrollGridView) appPager.getChildAt(appPager.getDisplayedChild()));
        if (resetFocus) {
            temp.setSelection(0);
            appPager.setFocusable(false);
            appPager.setFocusableInTouchMode(false);
        }
        if (temp.getAdapter().getCount() == 0)
            layout.showTips(getCurrentTips());
        else
            layout.hideTips();
        resetFocus = true;
        appPager.getChildAt(currentPage).setFocusable(true);
        appPager.getChildAt(currentPage).setFocusableInTouchMode(true);
        return false;
    }


    private SpannableString getCurrentTips() {
        String tips = "";
        SpannableString s = new SpannableString(tips);
        if (category_items != null && category_items.size() > currentPage) {
            if (tipsMap.get(category_items.get(currentPage).categoryId) != null)
                return tipsMap.get(category_items.get(currentPage).categoryId);
            if (category_items.get(currentPage).categoryId.equals(OWNWALLPAPER))
                tips = context.getResources().getString(R.string.setting_wallpaper_tips);
            else if (category_items.get(currentPage).categoryId.equals(MYCOLLECTION))
                tips = context.getResources().getString(R.string.setting_wallpaper_no_collect);
            else if (!Android.isNetConnected(context))
                tips = context.getResources().getString(R.string.setting_wallpaper_no_net);
            s = new SpannableString(tips);
            if (tips.contains("\n")) {
                int start = tips.indexOf("\n");
                s.setSpan(new ForegroundColorSpan(0xff88b8d9), start, tips.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                s.setSpan(new RelativeSizeSpan(0.8f), start, tips.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            tipsMap.put(category_items.get(currentPage).categoryId, s);
        }
        return s;
    }


    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    int total = category_items.get(currentPage).total;
                    int current = ((ScrollGridView) appPager.getChildAt(currentPage)).getAdapter().getCount() - 1;
                    if (current < total &&
                            ((GridView)v).getSelectedItemPosition() > (current - current % 4 - 1) && !Android.isNetConnected(context)) {
                        TipToast.getInstance(context).showTipToast(context.getResources().getString(R.string.please_connect_net));
                        return true;
                    }
                    break;
//                case KeyEvent.KEYCODE_DPAD_UP:
//                    if (appPager.getDisplayedChild() > 0 && v.getId() < 4){
//                        showPrePage();
//                        currentPage--;
//                        return true;
//                    }
//                    break;
            }
        }
        return false;
    }

    protected void showNextPage() {
        if (resetFocus) {
            appPager.setFocusable(true);
            appPager.setFocusableInTouchMode(true);
            appPager.requestFocus();
        }
        appPager.displayNextPage();
        appPager.setDisplayedChild(appPager.getDisplayedChild() + 1);
    }

    protected void showPrePage() {
        if (resetFocus) {
            appPager.setFocusable(true);
            appPager.setFocusableInTouchMode(true);
            appPager.requestFocus();
        }
        appPager.displayPrePage();
        appPager.setDisplayedChild(appPager.getDisplayedChild() - 1);
    }

    @Override
    public void titleSelected(int pos, String title) {
        resetFocus = false;
        appPager.getChildAt(pos).setFocusable(false);
        appPager.getChildAt(pos).setFocusableInTouchMode(false);
        if (currentPage < pos)
            showNextPage();
        else
            showPrePage();
        currentPage = pos;
    }

    private WallpaperAdapter getCurrentAdapter(){
        ScrollGridView gridView = getPage(currentPage);
        return (WallpaperAdapter)gridView.getAdapter();
    }

    @Override
    public void titleUnSelected() {
        ObjectAnimator anim = ObjectAnimator.ofFloat(appPager, "translationX", CoocaaApplication.Div(380), 0);
        anim.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                ScrollGridView current = ((ScrollGridView) appPager.getChildAt(appPager.getDisplayedChild()));
                current.requestFocus();
                current.setSelection(0);
                appPager.setFocusable(false);
                appPager.setFocusableInTouchMode(false);
                handler.sendEmptyMessageDelayed(SET_FOCUS_MSG, 100);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        anim.setDuration(300);
        anim.start();
        layout.showDivide(false);
        layout.getTitleBar().hideFocusView();
        layout.setFocusVewAlpha(0);
        ((ScrollGridView) appPager.getChildAt(currentPage)).showColumn(3, true);
    }

    @Override
    public void titleOnSelected() {
        LogUtils.d("wallpaper", "titleOnSelected");
        ObjectAnimator anim = ObjectAnimator.ofFloat(appPager, "translationX", 0, CoocaaApplication.Div(380));
        anim.setDuration(300);
        anim.start();
        anim.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                //getCurrentAdapter().setRefresh(true);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        layout.showDivide(true);
        layout.getTitleBar().setFocus(currentPage);
        layout.setFocusVewAlpha(0);
        for (int i = 0; i < category_items.size(); i++)
            ((ScrollGridView) appPager.getChildAt(i)).showColumn(3, false);
    }


    private static final int REFRESH_CATEGORY_MSG = 0;
    private static final int GET_LIST_MSG = 1;
    private static final int COLLECT_MSG = 2;
    private static final int SET_FOCUS_MSG = 3;
    private static final int RESET_FOCUS = 4;
    private static final int SET_GRIDVIEW_FOCUS = 5;
    private static final int HIDE_COL_MSG = 6;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH_CATEGORY_MSG:
                    if (category_items != null && category_items.size() > 0) {
                        layout.refreshTitleBar(category_items);
                        for (RP_WallpaperCategory.WallPaper_Category_Item item : category_items) {
                            LogUtils.i("wallpaper", "the " + item.categoryId + " and total is " + item.total);
                            getWallpaperList(item.categoryId, 0, PAGE_COUNT);
                        }
                        if (category_items.size() > 2) {
                            layout.getTitleBar().setFocus(2);
                            appPager.setDisplayedChild(2);
                            currentPage = 2;
                        } else {
                            layout.getTitleBar().setFocus(0);
                            appPager.setDisplayedChild(0);
                            currentPage = 0;
                        }
                    }
                    ((LauncherBaseActivity) (context)).hideLoading();
                    ((LauncherBaseActivity) (context)).hideLoading();
                    break;
                case GET_LIST_MSG:
                    String id = (String) msg.obj;
                    refreshContentById(id);
                    isGetdata = false;
                    break;
                case COLLECT_MSG:
                    break;
                case SET_FOCUS_MSG:
                    layout.setFocusVewAlpha(255);
                    layout.getTitleBar().enablePointViewFocus(true);
                    break;
                case RESET_FOCUS:
                    resetFocus();
                    break;
                case SET_GRIDVIEW_FOCUS:
                    appPager.getChildAt(currentPage).setFocusable(true);
                    appPager.getChildAt(currentPage).setFocusableInTouchMode(true);
                    break;
            }
        }
    };


    private void getCategory() {
        AsyncTask.runOnThread(new Runnable() {
            @Override
            public void run() {
                category_items = ContentApi.getWallpaperCategory();
                handler.sendEmptyMessage(REFRESH_CATEGORY_MSG);
            }
        });
    }

    private void refreshContentById(String id) {
        int pos = getPosByCategoryId(id);
        if (pos > -1) {
            if (wallpaper_items.get(id) != null) {
                if (category_items.get(currentPage).categoryId.equals(MYCOLLECTION)
                        && id.equals(MYCOLLECTION)
                        && currentPos >= wallpaper_items.get(id).size()) {
                    appPager.setFocusable(true);
                    appPager.requestFocus();
                }
                ((WallpaperAdapter)((ScrollGridView) appPager.getChildAt(pos)).
                        getAdapter()).refreshUI(wallpaper_items.get(id));
            }
        }
        if (pos == currentPage) {
            if (((ScrollGridView) appPager.getChildAt(pos)).getAdapter().getCount() == 0) {
                layout.showTips(getCurrentTips());
                if (!isPause && (id.equals(OWNWALLPAPER) || id.equals(MYCOLLECTION)))
                    layout.showTitleBar();
            } else {
                layout.hideTips();
            }
        }
    }


    private void getWallpaperList(final String id, final int index, final int count) {
        AsyncTask.runOnThread(new Runnable() {
            @Override
            public void run() {
                List<RP_WallpaperList.WallPaper_Item> temp = ContentApi.getWallpaperList(id, index, count);
                if (wallpaper_items.get(id) == null && temp != null) {
                    wallpaper_items.put(id, temp);
                } else if (temp != null) {
                    wallpaper_items.get(id).addAll(temp);
                }
                int result = 0;
                if (temp != null)
                    result = temp.size();
                LogUtils.i("wallpaper", "the id " + id + " index " + index + " count " + count + " result " + result);
                Message msg = handler.obtainMessage(GET_LIST_MSG);
                msg.obj = id;
                handler.sendMessage(msg);
            }
        });
    }


    public RP_WallpaperList.WallPaper_Item getWallpaperItem(int pos) {
        String id = category_items.get(currentPage).categoryId;
        if (wallpaper_items.get(id) != null && wallpaper_items.get(id).size() >= pos + 1) {
            if (wallpaper_items.get(id).size() < getCategoryById(id).total && wallpaper_items.get(id).size() - pos < PAGE_COUNT) {
                getWallpaperList(id, wallpaper_items.get(id).size() / PAGE_COUNT, PAGE_COUNT);
            }
            return wallpaper_items.get(id).get(pos);
        }
        return null;
    }


    private RP_WallpaperCategory.WallPaper_Category_Item getCategoryById(String id) {
        if (category_items != null) {
            for (RP_WallpaperCategory.WallPaper_Category_Item item : category_items) {
                if (item.categoryId.equals(id)) {
                    return item;
                }
            }
        }
        return new RP_WallpaperCategory.WallPaper_Category_Item("","","",0);
    }

    private int getPosByCategoryId(String id) {
        if (category_items != null){
            for (int i = 0; i < category_items.size(); i++) {
                if (category_items.get(i).categoryId.equals(id))
                    return i;
            }
        }
        return -1;
    }

    private boolean isGetdata = false;



    public void resume() {
        if (isPause){
            isPause = false;
            handler.sendEmptyMessageDelayed(RESET_FOCUS, 300);
        }
        //resetFocus();
    }

    public void pause() {
        isPause = true;
    }

    private void resetFocus() {
        if (appPager != null) {
            ScrollGridView page = getPage(currentPage);
            if (page != null && page.getAdapter().getCount() > 0) {
            } else {
                layout.showTitleBar();
            }
        }
        appPager.setFocusable(false);
    }


    private ScrollGridView getPage(int pos) {
        return (ScrollGridView) appPager.getChildAt(pos);
    }

    @Override
    public void onRightKey() {
        if (category_items != null && category_items.size() > 0){
            String id = category_items.get(currentPage).categoryId;
            if (wallpaper_items.get(id) != null && wallpaper_items.get(id).size() > 0){
                appPager.getChildAt(currentPage).setFocusable(true);
                appPager.getChildAt(currentPage).setFocusableInTouchMode(true);
                appPager.setFocusable(true);
                appPager.setFocusableInTouchMode(true);
                appPager.requestFocus();
            }
        }
    }

    public boolean updateCollect(RP_WallpaperList.WallPaper_Item item){
        String id = item.type;
        LogUtils.i("wallpaper","the type is " + item.type.toString() + " and id is " + id);
        List<RP_WallpaperList.WallPaper_Item> list = wallpaper_items.get(id);
        if (list == null)
            return false;
        for (RP_WallpaperList.WallPaper_Item temp : list){
            if (temp.id.equals(item.id)) {
                temp.isCollected = item.isCollected;
                refreshContentById(id);
                break;
            }
        }
        RP_WallpaperCategory.WallPaper_Category_Item category = getCategoryById(MYCOLLECTION);
        if (item.isCollected)
            category.total++;
        else
            category.total--;
        list = wallpaper_items.get(MYCOLLECTION);
        if (list != null)
            list.clear();
        getWallpaperList(MYCOLLECTION,0,PAGE_COUNT);
        return true;
    }

    private RP_WallpaperCategory.WallPaper_Category_Item getCategoryByType(String type) {
        if (category_items != null) {
            for (RP_WallpaperCategory.WallPaper_Category_Item item : category_items) {
                if (item.categoryId.equals(type))
                    return item;
            }
        }
        return null;
    }

    public void destory() {
        if (category_items != null)
            category_items.clear();
        wallpaper_items.clear();
        context.unregisterReceiver(wallpaperRecever);
        currentPage = 0;
        instance = null;
    }

    BroadcastReceiver wallpaperRecever = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            List<RP_WallpaperList.WallPaper_Item> list = wallpaper_items.get(OWNWALLPAPER);
            if (list != null)
                list.clear();
            getWallpaperList(OWNWALLPAPER, 0, PAGE_COUNT);
            String count = intent.getStringExtra("data");
            LogUtils.i("wallpaper", "the ownwallpaper count is " + count);
            if (count != null)
                getCategoryById(OWNWALLPAPER).total = Integer.valueOf(count);
            else
                getCategoryById(OWNWALLPAPER).total = 0;
        }
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        RP_WallpaperList.WallPaper_Item wallPaper_item = (RP_WallpaperList.WallPaper_Item)parent.getAdapter().getItem(position);
        if (!wallPaper_item.type.equals(OWNWALLPAPER) && !wallPaper_item.isCollected) {
            if (Android.isNetConnected(context)) {
                Intent intent = new Intent(context, WallpaperPreViewActivity.class);
                intent.putExtra("item", wallPaper_item.toString());
                intent.putExtra("pos", position);
                context.startActivity(intent);
            } else {
                TipToast.getInstance(context).showTipToast(context.getResources().getString(R.string.please_connect_net));
            }
        } else {
            Intent intent = new Intent(context, WallpaperPreViewActivity.class);
            intent.putExtra("item", wallPaper_item.toString());
            intent.putExtra("pos", position);
            context.startActivity(intent);
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long i) {
        LogUtils.d("pos","selected is " + position);
        currentPos = position;
        if (!isGetdata && category_items != null && category_items.size() > currentPage) {
            String id = category_items.get(currentPage).categoryId;
            LogUtils.d("wallpaper", "focus category id is " + id);
            if (wallpaper_items.get(id) != null){
                if (wallpaper_items.get(id).size() < getCategoryById(id).total && wallpaper_items.get(id).size() - currentPos < PAGE_COUNT) {
                    isGetdata = true;
                    getWallpaperList(id, wallpaper_items.get(id).size() / PAGE_COUNT, PAGE_COUNT);
                }
            }
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}
